package cc.uncarbon.module.appapi.service;


import cc.uncarbon.framework.core.exception.BusinessException;
import cc.uncarbon.module.appapi.mapper.ItemBannerMapper;
import cc.uncarbon.module.appapi.mapper.ItemMapper;
import cc.uncarbon.module.appapi.model.response.ItemBO;
import cc.uncarbon.module.appapi.model.vo.ItemVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yanrumiao.entity.ItemBannerEntity;
import com.yanrumiao.entity.ItemEntity;
import com.yanrumiao.util.ConvertUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 项目信息
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class ItemService {

    private final ItemMapper itemMapper;

    private final ItemBannerMapper itemBannerMapper;

    /**
     * 项目列表。
     *
     * @return 返回项目列表。
     */
    public List<ItemBO> getList(Long storeId) {
        LambdaQueryWrapper<ItemEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ItemEntity::getStatus, 1);
        wrapper.orderByAsc(ItemEntity::getSortOrder);

        List<ItemEntity> entityList = itemMapper.selectList(wrapper);
        ArrayList<ItemBO> bo = new ArrayList<>(entityList.size());
        entityList.forEach(entity -> bo.add(ConvertUtil.boToVo(entity, ItemBO.class)));
        return bo;


    }

    public ItemVO getOneByIdAndBanner(Long id) {
        ItemEntity entity = itemMapper.selectById(id);
        if (entity == null) {
            throw new BusinessException(400, "无效项目信息ID");
        }
        ItemVO vo = ConvertUtil.boToVo(entity, ItemVO.class);
        // 项目banner
        LambdaQueryWrapper<ItemBannerEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ItemBannerEntity::getItemId, id);
        wrapper.eq(ItemBannerEntity::getStatus, 1);
        wrapper.orderByAsc(ItemBannerEntity::getSort);

        List<ItemBannerEntity> list = itemBannerMapper.selectList(wrapper);
        vo.setBanner(new ArrayList<>(list.size()));
        //添加banner
        list.forEach(itemBannerEntity -> vo.getBanner().add(itemBannerEntity.getUrl()));

        return vo;
    }
    public ItemEntity getOneById(Long id){
        ItemEntity itemEntity = itemMapper.selectById(id);
        if (itemEntity == null) {
            throw new BusinessException(400, "无效项目信息ID");
        }
        return itemEntity;
    }
}
